<!-- src/views/index.vue -->
<template>
  <div class="excel-table-container">
    <div class="table-wrapper" ref="tableWrapper" @click="handleTableClick" @scroll="handleScroll" tabindex="0">
      <!-- 使用表头组件 -->
      <TableHeader
        :columns="columns"
        :header-scroll-left="headerScrollLeft"
        :selected-cells="selectedCells"
        :column-widths="columnWidths"
        :table-data="tableData"
        @handleColumnMenu="handleColumnContextMenu"
        @corner-mouse-down="handleCornerMouseDown($event)"
      />
      <!-- 表格内容 -->
      <div class="table-content">
        <!-- 行号列和数据列 -->
        <div v-for="(row, rowIndex) in tableData" :key="rowIndex" class="table-row"
             :class="{ selected: isRowSelectedAdapted(rowIndex) }">
          <div class="row-header" @contextmenu="handleContextMenu($event, rowIndex, null)"
               :class="{ selected: isRowSelectedAdapted(rowIndex) }">
            {{ rowIndex + 1 }}
          </div>
          <div class="row-cells">
            <div
              v-for="(cell, colIndex) in row"
              :key="colIndex"
              :data-cell-id="getCellId(rowIndex, colIndex)"
              class="data-cell"
              :class="{
                selected: isCellSelectedAdapted(rowIndex, colIndex),
                'drag-over': isDragOver(rowIndex, colIndex) || (dragOverCell && dragOverCell.row === rowIndex && dragOverCell.col === colIndex),
                editing: isEditing && editingCell.row === rowIndex && editingCell.col === colIndex
              }"
              :style="{
                width: getColumnWidth(colIndex) + 'px',
                minWidth: getColumnWidth(colIndex) + 'px',
                maxWidth: getColumnWidth(colIndex) + 'px'
              }"
              @contextmenu="handleContextMenu($event, rowIndex, colIndex)"
              @mousedown="handleCellMouseDownWrapper($event, rowIndex, colIndex)"
              @click="handleCellClick($event, rowIndex, colIndex, eiditing)"
              @dragenter="handleDragEnter($event, rowIndex, colIndex)"
              @dragleave="handleDragLeave($event)"
              @drop="handleDrop($event, rowIndex, colIndex)"
            >
              <!-- 编辑模式 -->
              <input
                v-if="isEditing && editingCell.row === rowIndex && editingCell.col === colIndex"
                v-model="editInputValue"
                class="edit-input"
                v-focus
                @blur="finishEditingHandler"
                @keyup.enter="finishEditingHandler"
                @keyup.esc="cancelEditingHandler"
                @click.stop
                @mousedown.stop
              />
              <!-- 查看模式 -->
              <div v-else class="cell-content" @mouseenter="showTooltip($event, cell.name)" @mouseleave="hideTooltip">
                {{ cell.name }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 拖拽预览 -->
      <div
        v-if="dragState.dragPreview.visible"
        class="drag-preview"
        :style="{
          left: dragState.dragPreview.x + 'px',
          top: dragState.dragPreview.y + 'px',
          width: dragState.dragPreview.width + 'px',
          height: dragState.dragPreview.height + 'px'
        }"
      >
        <div class="drag-preview-content">
          <div
            v-for="(cellData) in dragState.draggedCellsData"
            :key="`${cellData.row}-${cellData.col}`"
            class="drag-preview-cell"
            :style="getPreviewCellStyle(cellData)"
            :title="cellData.name"
          >
            <span class="cell-text">{{ cellData.name }}</span>
          </div>
        </div>
      </div>
      <!-- 全局 Tooltip -->
      <div v-if="tooltip.visible" class="custom-tooltip" :style="{ top: tooltip.y + 'px', left: tooltip.x + 'px' }">
        {{ tooltip.content }}
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import TableHeader from './compose/TableHeader.vue';
import { Cell, Column, TableState } from './types';
import { useDragDrop } from './composables/useDragDropManager';
import { useTooltip } from './composables/useTooltip';
import { useEditManager } from './composables/useEditManager';
import { useHistoryManager } from './composables/useHistoryManager';
import { useDataWatcher } from './composables/useDataWatcher';
import { useTableOperations } from './composables/useTableOperations';
import { useEventHandlers } from './composables/useEventHandlers';
import { useDragHandlers } from './composables/useDragHandlers';
import { useContextMenu } from './composables/useContextMenu';
// 定义 Props
const props = withDefaults(
  defineProps<{
    tableData?: Cell[][];
    columns?: Column[];
    enableDrag?: boolean;
    dragging?: boolean;
    eiditing?: boolean;
    onContextMenu?: (
      rowIndex: number,
      colIndex: number,
      allMenus: Array<any>
    ) => Array<{
      allMenus: Array<any>;
    }>;
  }>(),
  {
    tableData: () => [],
    columns: () => [],
    enableDrag: true,
    eiditing: true,
    dragging: true,
    onContextMenu: undefined
  }
);

// 然后正常初始化响应式数据
const columns = ref<Column[]>(props.columns);
const tableData = ref<Cell[][]>(props.tableData);
const selectedCells = ref<Set<string>>(new Set());
const tableWrapper = ref<HTMLElement | null>(null);

// 为每个组件实例创建独立的历史记录状态
const localHistory = ref<TableState[]>([]);
const localHistoryIndex = ref(-1);
// 添加列宽状态
const columnWidths = ref<number[]>([]);
const emit = defineEmits<{
  (e: 'update:tableData', data: Cell[][]): void;
  (e: 'update:columns', value: Column[]): void;
  (e: 'update:changeUnit', value: { row: number; col: number; oldValue: string; newValue: string }): void;
  (e: 'update:addRow'): void;
  (e: 'update:addCol'): void;
}>();

// 添加拖拽相关状态
const dragOverCell = ref<{ row: number; col: number } | null>(null);
// 使用历史记录管理模块，传入响应式数据引用
const { history, historyIndex, saveState, undo, redo } =
  useHistoryManager(tableData,
    columns,
    localHistory,
    localHistoryIndex);
// 使用数据监听器
useDataWatcher(props, columns, tableData, emit);

// 使用拖拽管理模块
const {
  dragState,
  isDragOver,
  setSelectedCells,
  getCellId,
  handleCellMouseDown,
  handleMouseMove,
  getPreviewCellStyle,
  moveSelectedCells,
  endDrag,
  clearSelection,
  selectCell,
  showDragPreviewForSelection,
  isRowSelected
} = useDragDrop(saveState);

// 使用编辑管理模块
const {
  isEditing,
  editingCell,
  editInputValue,
  clickTimer,
  CLICK_DELAY,
  enterEditMode,
  finishEditing,
  cancelEditing
} = useEditManager(emit);

const { tooltip, showTooltip, hideTooltip } = useTooltip();

const headerScrollLeft = ref(0);

// 替换原有的表格操作函数定义
const { addRow, addColumn } = useTableOperations(tableData, columns, selectedCells, saveState);

// 替换原有的事件处理函数定义
const {
  handleScroll,
  finishEditingHandler,
  cancelEditingHandler,
  handleCellClick,
  isRowSelectedAdapted,
  isCellSelectedAdapted,
  handleCornerMouseDown,
  handleTableClick,
  handleKeyDown,
  handleMouseUp,
  getColumnWidth
} = useEventHandlers(
  tableData,
  columns,
  selectedCells,
  dragState,
  isEditing,
  editingCell,
  editInputValue,
  clickTimer,
  CLICK_DELAY,
  headerScrollLeft,
  tableWrapper,
  columnWidths,
  history,
  historyIndex,
  getCellId,
  clearSelection,
  selectCell,
  enterEditMode,
  finishEditing,
  cancelEditing,
  moveSelectedCells,
  endDrag,
  showDragPreviewForSelection,
  saveState,
  undo,
  redo,
  isRowSelected
);
// 替换原有的拖拽处理函数定义
const { handleDragEnter, handleDragLeave, handleDrop } = useDragHandlers(
  props,
  tableData,
  columns,
  selectedCells,
  dragOverCell,
  clearSelection,
  getCellId,
  saveState,
  addRow,
  addColumn
);

const { handleContextMenu, hideCurrentContextMenu } = useContextMenu(tableData, columns, saveState, emit, props);
/**
 * 鼠标按下处理函数
 * @param event
 * @param rowIndex
 * @param colIndex
 */
const handleCellMouseDownWrapper = (event: MouseEvent, rowIndex: number, colIndex: number) => {
  hideCurrentContextMenu();
  // 只有在启用拖拽时才处理鼠标按下事件
  if (props.enableDrag) {
    handleCellMouseDown(event, rowIndex, colIndex, tableData.value, selectedCells.value, getCellId);
    // 如果是移动单元格模式，显示预览
    if (dragState.isMovingCells) {
      showDragPreviewForSelection(tableWrapper.value);
    }
  } else {
    // 禁用拖拽时，仍然允许单元格选择等基本功能
    handleCellMouseDown(event, rowIndex, colIndex, tableData.value, selectedCells.value, getCellId);
  }
};

/**
 * 鼠标移动处理函数
 * @param event
 */
const handleMouseMoveWrapper = (event: MouseEvent) => {
  if (props.enableDrag) {
    handleMouseMove(event, tableData.value, columns.value, tableWrapper.value, selectedCells.value, getCellId);
  }
};

// 修改 vFocus 指令，添加 preventScroll 选项
const vFocus = {
  mounted: (el: HTMLInputElement) => {
    el.focus({ preventScroll: true });
  }
};

const handleColumnContextMenu = (event: MouseEvent, colIndex: number) => {
  handleContextMenu(event, null, colIndex);
};
// 生命周期钩子
onMounted(() => {
  // 延迟执行 saveState，确保数据已经正确加载
  nextTick(() => {
    // 只有当数据不为空时才保存初始状态
    if (tableData.value.length > 0 || columns.value.length > 0) {
      saveState();
    }
  });

  // 其余初始化代码保持不变
  setSelectedCells(selectedCells.value);
  document.addEventListener('mousemove', handleMouseMoveWrapper);
  document.addEventListener('mouseup', handleMouseUp);
  document.addEventListener('keydown', handleKeyDown);

  // 添加全局拖拽事件监听
  if (props.dragging) {
    document.addEventListener('dragover', (e) => e.preventDefault());
    document.addEventListener('drop', (e) => e.preventDefault());
  }

  if (tableWrapper.value) {
    tableWrapper.value.setAttribute('tabindex', '0');
    tableWrapper.value.setAttribute('role', 'application');
    tableWrapper.value.addEventListener('click', () => {
      tableWrapper.value?.focus();
    });
  }
});

onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMoveWrapper);
  document.removeEventListener('mouseup', handleMouseUp);
  document.removeEventListener('keydown', handleKeyDown);

  // 清理拖拽事件
  if (props.dragging) {
    document.removeEventListener('dragover', (e) => e.preventDefault());
    document.removeEventListener('drop', (e) => e.preventDefault());
  }
});
</script>

<style scoped>
/* 父容器需要允许子元素居中或根据需要对齐 */
.excel-table-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

/* 工具栏优化 */
.excel-toolbar {
  padding: 12px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 8px;
  align-items: center;
}

.toolbar-btn {
  padding: 8px 16px;
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-btn:hover:not(:disabled) {
  background-color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.toolbar-btn:active:not(:disabled) {
  transform: translateY(0);
}

.btn-icon {
  font-size: 16px;
}

.shortcut {
  font-size: 11px;
  opacity: 0.7;
  margin-left: 4px;
}

.delete-btn {
  color: #fff;
  background-color: #ff6b6b;
  border-color: #ff6b6b;
}

.delete-btn:hover:not(:disabled) {
  background-color: #ff5252;
  border-color: #ff5252;
}

.delete-btn:disabled {
  background-color: #d9d9d9;
  border-color: #d9d9d9;
  cursor: not-allowed;
  opacity: 0.6;
}

/* 状态栏 */
.status-bar {
  padding: 6px 16px;
  background-color: #e9ecef;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: #6c757d;
}

.status-item {
  display: flex;
  align-items: center;
}

/* 表格容器优化 */
.table-wrapper {
  overflow: auto;
  position: relative;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: default;
  height: fit-content;
  width: fit-content;
  box-sizing: border-box;
  outline: none;
  max-width: calc(100% - 32px);
  max-height: calc(100vh - 200px);
}

.table-wrapper:focus {
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.2);
}

.table-content {
  position: relative;
}

/* 表格行 */
.table-row {
  display: flex;
  transition: background-color 0.2s ease;
}

.table-row:hover {
  background-color: #f8f9fa;
}

.table-row.selected .row-header {
  background-color: #cce7ff;
}

/* 行号列 */
.row-header {
  width: 40px;
  height: 35px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-right: 1px solid #dee2e6;
  border-bottom: 1px solid #dee2e6;
  text-align: center;
  font-weight: 600;
  cursor: pointer;
  position: sticky;
  left: 0;
  z-index: 15;
  flex-shrink: 0;
  display: flex;
  font-size: 13px;
  align-items: center;
  justify-content: center;
  color: #495057;
  transition: all 0.2s ease;
}

.row-header:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

.row-header.selected {
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  color: white;
}

/* 数据列容器 */
.row-cells {
  display: flex;
  align-items: center;
  flex: 1;
}

/* 数据单元格 */
.data-cell {
  height: 35px;
  border-right: 1px solid #e9ecef;
  border-bottom: 1px solid #e9ecef;
  padding: 2px 8px;
  position: relative;
  user-select: text;
  box-sizing: border-box;
  overflow: hidden;
  word-break: break-all;
  flex-shrink: 0;
  cursor: default;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
}

.data-cell:last-child {
  border-right: none;
}

.data-cell:hover {
  background-color: #f8f9fa;
}

.data-cell.selected {
  background-color: #73bfef;
  border-color: white;
  color: white;
}

.data-cell.drag-over {
  background-color: rgba(97, 177, 101, 0.3);
  border: 2px dashed #51cf66;
}

/* 单元格内容 */
.cell-content {
  width: 100%;
  max-width: 100%;
  overflow: hidden;
  font-size: 14px;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  position: relative;
  cursor: pointer;
  box-sizing: border-box;
  display: block;
  align-items: center;
  height: 100%;
  line-height: 31px;
}

/* 编辑模式 */
.data-cell.editing {
  padding: 0;
  border: 2px solid #339af0;
  z-index: 10;
}

.edit-input {
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
  padding: 2px 8px;
  box-sizing: border-box;
  font-size: 14px;
  background: transparent;
}

/* 拖拽预览优化 */
.drag-preview {
  position: absolute;
  background: linear-gradient(135deg, rgba(97, 177, 101, 0.3) 0%, rgba(81, 207, 102, 0.3) 100%);
  border: 2px solid #51cf66;
  pointer-events: none;
  z-index: 25;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  transition: all 0.3s ease;
  transform: scale(1);
  backdrop-filter: blur(4px);
}

.drag-preview.drag-active {
  transform: scale(1.02);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.drag-preview.drag-success {
  background: linear-gradient(135deg, rgba(81, 207, 102, 0.5) 0%, rgba(64, 192, 87, 0.5) 100%);
  transform: scale(1.05);
  transition: all 0.3s ease;
}

.drag-preview-content {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 2px;
  box-sizing: border-box;
}

.drag-preview-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  padding: 4px;
  box-sizing: border-box;
  border: 1px solid rgba(255, 255, 255, 0.3);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: white;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
  transition: all 0.2s ease;
}

.drag-preview-cell:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.02);
}

.cell-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

/* Tooltip 优化 */
.custom-tooltip {
  position: fixed;
  background: rgba(44, 44, 44, 0.95);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 13px;
  white-space: nowrap;
  z-index: 1000;
  pointer-events: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* 快捷键提示 */
.shortcut-hints {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 12px;
  font-size: 12px;
  color: #666;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(4px);
  z-index: 100;
}

.hint-item {
  padding: 4px 0;
  border-bottom: 1px solid #f0f0f0;
}

.hint-item:last-child {
  border-bottom: none;
}

/* 右键菜单样式 */
.table-context-menu {
  background: #ffffff;
  border: 1px solid #d0d7de;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10000;
  min-width: 160px;
}

.context-menu-item {
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
  color: #24292f;
  transition: background-color 0.1s ease;
}

.context-menu-item:hover {
  background-color: #f0f0f0;
}
</style>
